package server;

import common.Contact;

import java.io.*;
import java.net.Socket;
import java.util.List;

public class ResponseHandler implements Runnable {
    private final Socket clientSocket;
    private final ContactManager contactManager;

    public ResponseHandler(Socket clientSocket, ContactManager contactManager) {
        this.clientSocket = clientSocket;
        this.contactManager = contactManager;
    }

    @Override
    public void run() {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()))) {

            String request = reader.readLine();
            String[] parts = request.split(":");

            switch (parts[0]) {
                case "VIEW":
                    List<Contact> contacts = contactManager.getContacts();
                    writer.write(String.join(", ", contacts.toString()) + "\n");
                    break;
                case "ADD":
                    contactManager.addContact(parts[1], parts[2]);
                    writer.write("联系人添加成功\n");
                    break;
                case "DELETE":
                    contactManager.deleteContact(parts[1]);
                    writer.write("联系人删除成功\n");
                    break;
                case "UPDATE":
                    contactManager.updateContact(parts[1], parts[2]);
                    writer.write("联系人更新成功\n");
                    break;
                default:
                    writer.write("无效请求\n");
            }

            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
